package cn.cxyxj.study06.email;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 邮箱身份验证提供者
 * @author cxyxj
 */
public class EmailVerificationCodeAuthenticationProvider implements AuthenticationProvider {

    private EmailVerificationCodeService service;

    public EmailVerificationCodeAuthenticationProvider(EmailVerificationCodeService service) {
        this.service = service;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String email = authentication.getName();
        // 根据邮箱加载用户信息
        UserDetails userDetails = service.loadUserByEmail(email);
        if (userDetails == null) {
            // 可以自定义异常类型
            throw new InternalAuthenticationServiceException("邮箱方式登录异常");
        }
        EmailVerificationCodeAuthenticationToken result = new EmailVerificationCodeAuthenticationToken(userDetails,
                userDetails.getAuthorities());
        result.setDetails(authentication.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (EmailVerificationCodeAuthenticationToken.class
                .isAssignableFrom(authentication));
    }

}
